package com.inspinia.base.api.controller;

import com.inspinia.base.api.jwt.JWTConfig;
import com.inspinia.base.api.jwt.JWTGenerator;
import com.inspinia.base.api.model.ApiException;
import com.inspinia.base.api.service.InterfaceUserService;
import com.inspinia.base.common.exception.ApiErrorCode;
import com.inspinia.base.common.model.AjaxResult;
import com.inspinia.base.common.model.BaseConstants;
import com.inspinia.base.common.model.KeyParameters;
import com.inspinia.base.util.JsonUtils;
import com.inspinia.base.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Created by frank_zhu on 2017/6/30.
 */
@Controller
@RequestMapping("api/keyGenerator")
public class JWTKeyGeneratorController {

    @Resource
    private InterfaceUserService interfaceUserService;

    @ResponseBody
    @RequestMapping(value = "getKey", method = RequestMethod.POST)
    public AjaxResult getKey(@RequestBody KeyParameters keyParameters) {
        try {
            validateParameter(keyParameters);

            Long userId = interfaceUserService.userValidate(keyParameters);
            keyParameters.setUserId(userId);

            String jwt = JWTGenerator.createJWT(JsonUtils.toJson(keyParameters), JWTConfig.ISSUER, keyParameters.getUserName(), BaseConstants.ONE_DAY_MS, JWTConfig.SECRET);
            return new AjaxResult(true, jwt);

        } catch (ApiException e) {
            return new AjaxResult(false, e.getErrorCode(), e.getMessage());
        }

    }

    /**
     * 验证参数是否有效
     *
     * @param keyParameters
     * @return
     */
    private boolean validateParameter(KeyParameters keyParameters) {

        if (null != keyParameters && (keyParameters.getCalleeCityId() != null || keyParameters.getCalleeProvinceId() != null) && StringUtils.isNotBlank(keyParameters.getUserName())) {
            return true;
        }
        throw new ApiException(ApiErrorCode.externalApiParametersError);

    }

}
